<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <div>
        <div class="page_top">
            <div class="left_btn" @click="back">
                <img src="../../assets/image/back.png" alt=""/>
            </div>
            <crumbs basetitle="客户" title="保险客户管理" title1=""></crumbs>
        </div>
        <div class="w-full box-border p-16px">
            <el-card class="mb-16px">
                <filterComponentPro noEmit v-model:filter-data="filterData" @doSearch="handleSearch">
                    <template #header>
                        <div class="flex items-center gap-10px">
                            <el-select class="!w-350px" clearable v-model="companyId" filterable remote reserve-keyword
                                       placeholder="智能搜索客户名称或客户ID数字" :remote-method="remoteMethod"
                                       :loading="loading">
                                <template #prefix>
                                    <el-icon>
                                        <Search/>
                                    </el-icon>
                                </template>
                                <el-option v-for="item in companyList" :key="item.id" :label="item.companyName"
                                           :value="item.id"/>
                            </el-select>
                            <div @click="onExportCompanyList" class="flex items-center gap-5px cursor-pointer">
                                <img class="w-16px h-16px mt--1px" src="../../assets/image/Share.png" alt=""/>
                                <span class="text-14px text-#9497b1">导出客户列表</span>
                            </div>
                            <el-popover placement="bottom-start" title="" :width="100" trigger="hover">
                                <div class="text-center cursor-pointer text-#0256ff" @click="onExportTbkh">
                                    投保客户信息
                                </div>
                                <div class="text-center cursor-pointer text-#0256ff" @click="onExportBxxd">保险详单
                                </div>
                                <template #reference>
                                    <div class="flex items-center gap-5px cursor-pointer">
                                        <img class="w-16px h-16px mt--1px" src="../../assets/image/Share.png" alt=""/>
                                        <span class="text-14px text-#9497b1">投保导出</span>
                                    </div>
                                </template>
                            </el-popover>
                        </div>
                    </template>
                </filterComponentPro>
            </el-card>
            <el-card>
                <tableComponent :table-header="tableHeader" selection @selectionChange="selectionChange"
                                :table-data="tableData" border v-model:page-info="pageInfo"
                                @pageChange="handlePageChange">
                    <template #adminName>
                        <el-table-column prop="adminName" label="超管" align="center" width="150">
                            <template #default="scope">
                                <el-popover placement="bottom" title="" effect="dark" :width="200" trigger="hover" content="">
                                   <div class="text-#ffffff text-center">手机号：{{scope.row.adminPhone}}</div>
                                    <template #reference>
                                        <div class="underline-black underline">{{
                                                scope.row.adminName
                                            }}
                                        </div>
                                    </template>
                                </el-popover>
                            </template>
                        </el-table-column>
                    </template>
                    <template #isOpenPaySalary>
                        <el-table-column prop="isOpenPaySalary" label="子弹发薪" align="center" width="150">
                            <template #default="scope">
                                <div v-if="scope.row.isOpenPaySalary === 1" class="flex flex-col gap-10px">
                                    <div>剩余{{ scope.row.paySurplusDays }}天</div>
                                    <el-popover placement="bottom" title="" :width="200" trigger="click" content="">
                                        <el-select filterable class="w-full" v-model="sj.saleId" placeholder="搜索姓名"
                                                   @change="changeSale">
                                            <el-option v-for="item in allseller" :key="item.saleId"
                                                       :label="item.saleName" :value="item.saleId"/>
                                        </el-select>
                                        <template #reference>
                                            <div class="b_d" @click="openzdfxchange(scope.row)">{{
                                                    scope.row.paySaleName
                                                }}
                                                <el-icon>
                                                    <ArrowDown/>
                                                </el-icon>
                                            </div>
                                        </template>
                                    </el-popover>
                                </div>
                                <div v-if="scope.row.isOpenPaySalary === 0">
                                    <div>未开通</div>
                                </div>
                            </template>
                        </el-table-column>
                    </template>
                    <template #isOpenPeriod>
                        <el-table-column prop="isOpenPeriod" label="长期保" align="center" width="200">
                            <template #default="scope">
                                <div v-if="scope.row.isOpenPeriod === 1" class="flex flex-col gap-10px">
                                    <div>¥{{ scope.row.periodAccountBalance }}</div>
                                    <div class="b_d flex-center">
                                        <el-tag v-if="scope.row.insureBlackList" class="ml-2" type="info"
                                                color="#BDBEC3"><span class="fc-black">拉黑</span>
                                        </el-tag>
                                        <el-tag v-if="scope.row.periodInsureStatus?.refusalGuaranteeStatus" class="ml-2"
                                                type="danger">拒保
                                        </el-tag>
                                        <el-tag v-if="scope.row.periodInsureStatus?.blockedAccount" class="ml-2"
                                                type="danger">冻结
                                        </el-tag>
                                        <el-tag v-if="scope.row.periodInsureStatus?.antiDatedPolicy" class="ml-2"
                                                type="danger">倒投保
                                        </el-tag>
                                    </div>
                                    <el-popover placement="bottom" title="" :width="200" trigger="click" content="">
                                        <el-select filterable style="width: 100%;" v-model="sj.saleId"
                                                   placeholder="搜索姓名" @change="changeSale">
                                            <el-option v-for="item in allseller" :key="item.saleId"
                                                       :label="item.saleName" :value="item.saleId"/>
                                        </el-select>
                                        <template #reference>
                                            <div class="b_d" @click="openlongchange(scope.row)">{{
                                                    scope.row.periodSaleName
                                                }}
                                                <el-icon>
                                                    <ArrowDown/>
                                                </el-icon>
                                            </div>
                                        </template>
                                    </el-popover>
                                </div>
                                <div v-if="scope.row.isOpenPeriod === 0">
                                    <div>未开通</div>
                                    <el-tag v-if="scope.row.insureBlackList" class="ml-2" type="info"
                                            color="#BDBEC3"><span class="fc-black">拉黑</span>
                                    </el-tag>
                                </div>
                            </template>
                        </el-table-column>
                    </template>

                    <template #isOpenWesure>
                        <el-table-column prop="isOpenWesure" label="日日保" align="center" width="150">
                            <template #default="scope">
                                <div v-if="scope.row.isOpenWesure === 1" class="flex flex-col gap-10px">
                                    <div>¥{{ scope.row.wesureAccountBalance }}</div>
                                    <div class="b_d flex-center">
                                        <el-tag v-if="scope.row.wesurBlackList" class="ml-2" type="info"
                                                color="#BDBEC3"><span class="fc-black">拉黑</span>
                                        </el-tag>
                                        <el-tag v-if="scope.row.weusreStatus?.refusalGuaranteeStatus" class="ml-2"
                                                type="danger">拒保
                                        </el-tag>
                                        <el-tag v-if="scope.row.weusreStatus?.blockedAccount" class="ml-2"
                                                type="danger">冻结
                                        </el-tag>
                                        <el-tag v-if="scope.row.weusreStatus?.antiDatedPolicy" class="ml-2"
                                                type="danger">倒投保
                                        </el-tag>
                                    </div>
                                    <el-popover placement="bottom" title="" :width="200" trigger="click" content="">
                                        <el-select filterable style="width: 100%;" v-model="sj.saleId"
                                                   placeholder="搜索姓名" @change="changeSale">
                                            <el-option v-for="item in allseller" :key="item.saleId"
                                                       :label="item.saleName" :value="item.saleId"/>
                                        </el-select>
                                        <template #reference>
                                            <div class="b_d" @click="opendaychange(scope.row)">{{
                                                    scope.row.wesureSaleName
                                                }}
                                                <el-icon>
                                                    <ArrowDown/>
                                                </el-icon>
                                            </div>
                                        </template>
                                    </el-popover>
                                </div>
                                <div v-if="scope.row.isOpenWesure === 0">
                                    <div>未开通</div>
                                    <el-tag v-if="scope.row.wesurBlackList" class="ml-2" type="info"
                                            color="#BDBEC3"><span class="fc-black">拉黑</span>
                                    </el-tag>
                                </div>
                            </template>
                        </el-table-column>
                    </template>

                    <template #isOpenTyrbStatus>
                        <el-table-column prop="isOpenTyrbStatus" label="团意日保" align="center" width="150">
                            <template #default="scope">
                                <div v-if="scope.row.isOpenTyrbStatus === 1" class="flex flex-col gap-10px">
                                    <div>已开通</div>
                                    <el-popover placement="bottom" title="" :width="200" trigger="click" content="">
                                        <el-select filterable style="width: 100%;" v-model="sj.saleId"
                                                   placeholder="搜索姓名" @change="changeSale">
                                            <el-option v-for="item in allseller" :key="item.saleId"
                                                       :label="item.saleName" :value="item.saleId"/>
                                        </el-select>
                                        <template #reference>
                                            <div class="b_d" @click="opentyrbchange(scope.row)">{{
                                                    scope.row.tyxSaleName
                                                }}
                                                <el-icon>
                                                    <ArrowDown/>
                                                </el-icon>
                                            </div>
                                        </template>
                                    </el-popover>
                                </div>
                                <div v-if="scope.row.isOpenTyrbStatus === 0">
                                    <div>未开通</div>
                                </div>
                            </template>
                        </el-table-column>
                    </template>

                    <template #isOpenEleSign>
                        <el-table-column prop="isOpenEleSign" label="电子签" align="center" width="200">
                            <template #default="scope">
                                <div v-if="scope.row.isOpenEleSign === 1" class="flex flex-col gap-10px">
                                    <div>¥{{ scope.row.eleAccountBalance }}</div>
                                    <el-popover placement="bottom" title="" :width="200" trigger="click" content="">
                                        <el-select filterable style="width: 100%;" v-model="sj.saleId"
                                                   placeholder="搜索姓名" @change="changeSale">
                                            <el-option v-for="item in allseller" :key="item.saleId"
                                                       :label="item.saleName" :value="item.saleId"/>
                                        </el-select>
                                        <template #reference>
                                            <div class="b_d" @click="openelechange(scope.row)">{{
                                                    scope.row.eleSaleName
                                                }}
                                                <el-icon>
                                                    <ArrowDown/>
                                                </el-icon>
                                            </div>
                                        </template>
                                    </el-popover>
                                </div>
                                <div v-if="scope.row.isOpenEleSign === 0">
                                    <div>未开通</div>
                                </div>
                            </template>
                        </el-table-column>
                    </template>
                    <template #operate>
                        <el-table-column prop="operate" label="操作" width="120" align="center" fixed="right">
                            <template #default="scope">
                                <div class="w-full box-border flex items-center justify-center">
                                    <el-button link type="primary" @click.prevent="detail(scope.row)">查看详情
                                    </el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </template>
                </tableComponent>
            </el-card>
        </div>
        <bxxdDialog v-model:show="bxxdIsup"></bxxdDialog>
        <tbkhDialog v-model:show="tbkhIsup"></tbkhDialog>
    </div>
</template>

<script setup lang="ts">
import bxxdDialog from './export-dialog/bxxd-dialog.vue'
import tbkhDialog from './export-dialog/tbkh-dialog.vue'
import crumbs from '@/components/crumbs.vue'
import {useRouter} from 'vue-router'
import filterComponentPro from '@/components/filterComponentPro/index.vue'
import tableComponent from '@/components/tableComponent/index.vue'
import {ArrowDown, Search} from '@element-plus/icons-vue'
import {onMounted, ref} from 'vue'
import {
    getcompanyapi,
    getditchapi,
    geteverydayinsuranceaudicompanytapi,
    getlongtimeinsuranceaudicompanytapi,
    getclientsapi,
    setmarketapi,
    changemarketapi,
    getmarketapi,
    exportcompanylistapi
} from '@/api/api'
import {ElMessage} from 'element-plus'
import dayjs from 'dayjs'
import baseurl from '@/api/env'

const router = useRouter()
const bxxdIsup = ref(false)
const tbkhIsup = ref(false)
const sj = ref<any>({
    companyId: '',
    id: '',
    productType: '',
    saleId: '',
    saleOldId: '',
    serviceStartTime: '',
    serviceState: 0,
})
const companyId = ref('')
const filterData = ref({
    list: {
        productType: {
            name: '产品类型',
            prop: 'productType',
            value: '',
            placeholder: '请选择产品类型',
            type: 'select',
            options: [
                {
                    value: '1',
                    label: '日日保',
                },
                {
                    value: '2',
                    label: '长期保',
                },
                {
                    value: '3',
                    label: '团意保',
                }
            ],
            defaultAttrs: {
                label: 'label',
                value: 'value'
            },
            handleChange: async (item: any) => {
                if (!item.value) {
                    filterData.value.list.insureCompanyType.value = ''
                    filterData.value.list.insureCompanyType.placeholder = '请先选择产品类型'
                    filterData.value.list.insureCompanyType.options = []
                } else {
                    const apiMap = {
                        '1': geteverydayinsuranceaudicompanytapi,
                        '2': getlongtimeinsuranceaudicompanytapi,
                        '3': geteverydayinsuranceaudicompanytapi,
                    }
                    filterData.value.list.insureCompanyType.options = await apiMap[item.value as keyof typeof apiMap]() as any
                    filterData.value.list.insureCompanyType.placeholder = '请选择保险公司'
                }
                filterData.value.list.insureCompanyType.disabled = !item.value
            }
        },
        insureCompanyType: {
            name: '保险公司',
            prop: 'insureCompanyType',
            value: '',
            disabled: true,
            placeholder: '请先选择产品类型',
            type: 'select',
            options: [],
            defaultAttrs: {
                label: 'dictLabel',
                value: 'dictValue'
            },
        },
        channelId: {
            name: '渠道账户 ',
            prop: 'channelId',
            value: '',
            placeholder: '请先选择渠道账户',
            type: 'select',
            options: [],
            defaultAttrs: {
                label: 'name',
                value: 'id'
            },
        },
        balanceType: {
            name: '余额状态',
            prop: 'balanceType',
            value: '',
            placeholder: '请选择余额状态',
            type: 'select',
            options: [
                {
                    value: '0',
                    label: '全部',
                },
                {
                    value: '1',
                    label: '有余额',
                },
                {
                    value: '2',
                    label: '余额为零',
                },
            ],
            defaultAttrs: {
                label: 'label',
                value: 'value'
            }
        },
        auditStatus: {
            name: '账号状态',
            prop: 'auditStatus',
            value: '',
            placeholder: '请选择审核状态',
            type: 'select',
            options: [
                {
                    value: '0',
                    label: '待审核',
                },
                {
                    value: '1',
                    label: '审核通过',
                },
                {
                    value: '2',
                    label: '审核驳回',
                },
            ],
            defaultAttrs: {
                label: 'label',
                value: 'value'
            }
        },
        saleName: {
            name: '所属销售',
            prop: 'saleName',
            value: '',
            placeholder: '请输入销售姓名/手机号',
            type: 'input'
        },
        adminName: {
            name: '超管信息',
            prop: 'adminName',
            value: '',
            placeholder: '请输入超管姓名/手机号',
            type: 'input'
        },
        month: {
            name: '开户时间',
            type: 'date',
            prop: 'month',
            dateType: 'daterange',
            value: '',
            valueFormat: 'YYYY-MM-DD',
        }
    },
    buttonList: []
})
const pageInfo = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
})
const tableHeader = ref([
    {
        label: '客户ID',
        prop: 'companyId',
        width: 120
    },
    {
        label: '客户名',
        prop: 'companyName',
        width: 200
    },
    {
        label: '超管',
        prop: 'adminName',
        width: 200
    },
    {
        label: '账号状态',
        prop: 'auditStatus',
        width: 200,
        map: {
            0: '待审核',
            1: '审核通过',
            2: '审核驳回',
        }
    },
    {
        label: '子弹发薪',
        prop: 'isOpenPaySalary',
        width: 200
    },
    {
        label: '长期保',
        prop: 'isOpenPeriod',
        width: 200
    },
    {
        label: '日日保',
        prop: 'isOpenWesure',
        width: 200
    },
    {
        label: '团意日保',
        prop: 'isOpenTyrbStatus',
        width: 200
    },
    {
        label: '电子签',
        prop: 'isOpenEleSign',
        width: 200
    },
    // {
    //     label: '开户时间',
    //     prop: 'isOpenPeriod',
    //     width: 200
    // },
    {
        label: '操作',
        prop: 'operate'
    }
])
const loading = ref(false)
const tableData = ref([1])
const companyList = ref([] as {
    id: number,
    companyName: string,
}[])
const allseller = ref<any>([])
const selectList = ref([])
const selectionChange = (selection: any) => {
    selectList.value = selection
}
const getmarket = async () => {
    allseller.value = await getmarketapi()
}
const openzdfxchange = (res: any) => {
    sj.value.id = res.payDealId
    sj.value.saleOldId = res.paySaleId
    sj.value.companyId = res.companyId
    sj.value.productType = 0
    sj.value.serviceStartTime = dayjs().startOf('month').format('YYYY-MM-DD')
}
const openlongchange = (res: any) => {
    sj.value.id = res.periodDealId
    sj.value.saleOldId = res.periodSaleId
    sj.value.companyId = res.companyId
    sj.value.productType = 3
    sj.value.serviceStartTime = dayjs().startOf('month').format('YYYY-MM-DD')
}
const opendaychange = (res: any) => {
    sj.value.id = res.wesureDealId
    sj.value.saleOldId = res.wesureSaleId
    sj.value.companyId = res.companyId
    sj.value.productType = 2
    sj.value.serviceStartTime = dayjs().startOf('month').format('YYYY-MM-DD')
}
const opentyrbchange = (res: any) => {
    sj.value.id = res.tyxDealId
    sj.value.saleOldId = res.tyxSaleId
    sj.value.companyId = res.companyId
    sj.value.productType = 6
    sj.value.serviceStartTime = dayjs().startOf('month').format('YYYY-MM-DD')
}
const openelechange = (res: any) => {
    sj.value.companyId = res.companyId
    sj.value.id = res.eleDealId
    sj.value.saleOldId = res.eleSaleId
    sj.value.productType = 1
    sj.value.serviceStartTime = dayjs().startOf('month').format('YYYY-MM-DD')
}
const changeSale = () => {
    if (!sj.value.saleOldId) {
        setmarketapi({
            companyId: sj.value.companyId,
            id: sj.value.id,
            productType: sj.value.productType,
            saleId: sj.value.saleId,
            serviceStartTime: sj.value.serviceStartTime,
            serviceState: sj.value.serviceState,
        }).then((res: any) => {
            console.log(res)
            if (res.code === 200) {
                getData()
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            }
        })
    } else {
        changemarketapi(sj.value).then((res: any) => {
            console.log(res)
            if (res.code === 200) {
                getData()
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            }
        })
    }
    sj.value.companyId = ''
    sj.value.id = ''
    sj.value.productType = ''
    sj.value.saleId = ''
    sj.value.saleOldId = ''
    sj.value.serviceStartTime = ''
}
const back = () => {
    window.history.back()
}
const getDitch = async () => {
    filterData.value.list.channelId.options = await getditchapi() as any
}
const getCompany = async (val: any) => {
    const res: any = await getcompanyapi(val)
    console.log(res, '获取公司列表')
    companyList.value = res
    const statusMap = {
        0: '待审核',
        1: '审核通过',
        2: '审核驳回',
    } as any
    companyList.value.forEach((i: any) => {
        i.companyName =
            i.companyName +
            (i.auditStatus || i.auditStatus === 0
                ? `（${statusMap[i.auditStatus]}）`
                : '')
    })
    loading.value = false
}
const remoteMethod = (query: string) => {
    if (query) {
        loading.value = true
        getCompany(query)
    } else {
        companyList.value = []
    }
}
const detail = (ele: any) => {
    router.push({path: '/cockpit', query: {id: ele.companyId}})
}
const handleSearch = () => {
    getData()
}
const handlePageChange = () => {
    getData()
}
const getData = async () => {
    const res: any = await getclientsapi({
        companyId: companyId.value,
        auditStatus: filterData.value.list.auditStatus.value,
        adminName: filterData.value.list.adminName.value,
        pageSize: pageInfo.value.pageSize,
        channelId: filterData.value.list.channelId.value,
        pageNum: pageInfo.value.pageNum,
        saleName: filterData.value.list.saleName.value,
        balanceType: filterData.value.list.balanceType.value,
        isOpenWesure: filterData.value.list.productType.value === '1' ? 1 : '',
        isOpenTyrbStatus: filterData.value.list.productType.value === '3' ? 1 : '',
        isOpenPeriod: filterData.value.list.productType.value === '2' ? 1 : '',
    })
    tableData.value = res.list
    pageInfo.value.total = res.totalCount
}
const onExportCompanyList = async () => {
    console.log(selectList.value, '导出')
    if (selectList.value.length === 0) {
        ElMessage({
            message: '请选择公司',
            type: 'warning',
        })
    } else {
        const arr: any = []
        selectList.value.forEach((ele: any) => {
            arr.push(ele.companyId)
        })
        await exportcompanylistapi(arr).then((res: any) => {
            window.location.href =
                baseurl + '/common/download?delete=true&fileName=' + res
            selectList.value = []
        })
    }
}
const onExportBxxd = () => {
    bxxdIsup.value = true
}
const onExportTbkh = () => {
    tbkhIsup.value = true
}
onMounted(async () => {
    await getDitch()
    await getmarket()
    await getData()
})
</script>

<style scoped lang="scss"></style>